const { Controller } = require("egg");

class CommentController extends Controller {
    /**
     * 添加评论
     */
    async create() {
        // 解构请求体参数
        const { content, bid } = this.ctx.request.body;
        // 获取当前登录用户的id
        const { id } = this.ctx.user;
        // 校验要评论的博客存不存在
        const blog = await this.service.blog.find(bid);
        if (!blog) {
            this.ctx.body = {
                code: 404,
                message: "要评论的博客不存在",
            };
            return;
        }
        // 存数据库
        const res = await this.service.comment.addComment(content, bid, id);
        // 判断是否添加成功
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: "添加失败",
            };
        } else {
            this.ctx.body = {
                code: 201,
                message: "添加成功",
            };
        }
    }

    /**
     * 评论列表
     */
    async index() {
        // 解构路径参数
        const { bid } = this.ctx.params;
        const res = await this.service.comment.readListByBid(bid);
        this.ctx.body = {
            code: 200,
            data: res,
            message: "请求成功",
        };
    }
}

module.exports = CommentController;
